package common.spring.redis;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;


import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * redis工具类
 */

public class RedisUnits extends RedisTemplate {

    RedisTemplate<String, Object> redisTemplate;

    private final Logger LOG = LoggerFactory.getLogger(RedisUnits.class);

    private RedisUnits() {
        redisTemplate = this;
    }


    private boolean isEmpty(Object obj) {
        if (obj == null) {
            return true;
        }
        if (obj instanceof String) {
            String str = obj.toString();
            if ("".equals(str.trim())) {
                return true;
            }
            return false;
        }
        if (obj instanceof List) {
            List<Object> list = (List<Object>) obj;
            if (list.isEmpty()) {
                return true;
            }
            return false;
        }
        if (obj instanceof Map) {
            Map map = (Map) obj;
            if (map.isEmpty()) {
                return true;
            }
            return false;
        }
        if (obj instanceof Set) {
            Set set = (Set) obj;
            if (set.isEmpty()) {
                return true;
            }
            return false;
        }
        if (obj instanceof Object[]) {
            Object[] objs = (Object[]) obj;
            if (objs.length <= 0) {
                return true;
            }
            return false;
        }
        return false;
    }

    //序列化
    public static byte [] serialize(Object obj){
        ObjectOutputStream obi=null;
        ByteArrayOutputStream bai=null;
        try {
            bai=new ByteArrayOutputStream();
            obi=new ObjectOutputStream(bai);
            obi.writeObject(obj);
            byte[] byt=bai.toByteArray();
            return byt;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //反序列化
    public static Object unserizlize(byte[] byt){
        ObjectInputStream oii=null;
        ByteArrayInputStream bis=null;
        bis=new ByteArrayInputStream(byt);
        try {
            oii=new ObjectInputStream(bis);
            Object obj=oii.readObject();
            return obj;
        } catch (Exception e) {

            e.printStackTrace();
        }
        return null;
    }
    /**
     * 判断key值是否存在
     *
     * @param key 缓存的key
     * @return true:存在 false:不存在
     */
    public boolean hasKey(String key) {
        LOG.debug(" hasKey key :{}", key);
        try {
            if (isEmpty(key)) {
                return false;
            }
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 匹配符合正则的key
     *
     * @param patternKey
     * @return key的集合
     */
    public Set<String> keys(String patternKey) {
        LOG.debug(" keys key :{}", patternKey);
        try {
            if (isEmpty(patternKey)) {
                return Collections.emptySet();
            }
            return redisTemplate.keys(patternKey);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return Collections.emptySet();
    }

    /**
     * 根据key删除缓存
     *
     * @param key
     * @return true:成功 false:失败
     */
    public boolean del(String... key) {
        LOG.debug(" delete key :{}", key.toString());
        try {
            if (isEmpty(key)) {
                return false;
            }
            Set<String> keySet = new HashSet<>();
            for (String str : key) {
                keySet.add(str);
            }
            redisTemplate.delete(keySet);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 根据key删除缓存
     *
     * @param key
     * @return true:成功 false:失败
     */
    public boolean delPattern(String key) {
        LOG.debug(" delete Pattern keys :{}", key);
        try {
            if (isEmpty(key)) {
                return false;
            }
            redisTemplate.delete(redisTemplate.keys(key));
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 删除一组key值
     *
     * @param keys
     * @return true:成功 false:失败
     */
    public boolean del(Set<String> keys) {
        LOG.debug(" delete keys :{}", keys.toString());
        try {
            if (isEmpty(keys)) {
                return false;
            }
            Set<String> keySet = new HashSet<>();
            for (String str : keys) {
                keySet.add(str);
            }
            redisTemplate.delete(keySet);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 设置过期时间（秒）
     *
     * @param key     缓存key
     * @param seconds 过期秒数
     * @return true:成功 false:失败
     */
    public boolean setExp(String key, long seconds) {
        LOG.debug(" setExp key :{}, seconds: {}", key, seconds);
        try {
            if (isEmpty(key) || seconds < 0) {
                return false;
            }
            return redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 设置过期时间（天）
     *
     * @param key 缓存key
     * @param day 过期天数
     * @return true:成功 false:失败
     */
    public boolean setExpDay(String key, long day) {
        LOG.debug(" setExp key :{}, seconds: {}", key, day);
        try {
            if (isEmpty(key) || day < 0) {
                return false;
            }

            return redisTemplate.expire(key, day, TimeUnit.DAYS);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 查询过期时间(秒)
     *
     * @param key 缓存key
     * @return 秒数
     */
    public Long getExpire(String key) {
        LOG.debug(" getExpire key :{}", key);
        try {
            if (isEmpty(key)) {
                return 0L;
            }

            return redisTemplate.getExpire(key);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return 0L;
    }

    /**
     * 查询过期时间(天)
     *
     * @param key 缓存key
     * @return 秒数
     */
    public Long getExpireDay(String key) {
        LOG.debug(" getExpire key :{}", key);
        try {
            if (isEmpty(key)) {
                return 0L;
            }
            return redisTemplate.getExpire(key, TimeUnit.DAYS);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return 0L;
    }

    /**
     * 去的缓存中的最大值并+1
     *
     * @param key 缓存key值
     * @return long    缓存中的最大值+1
     */
    public long incr(String key) {
        LOG.debug(" incr key :{}", key);
        try {
            if (isEmpty(key)) {
                return 0;
            }

            return redisTemplate.opsForValue().increment(key, 1);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return 0;
    }

    /**
     * 缓存中存入序列化的Object对象
     *
     * @param
     * @param key 缓存key
     * @param obj 存入的序列化对象
     * @return true:成功 false:失败
     */
    public boolean set(String key, Object obj) {
        LOG.debug(" set key :{}, value:{}", key, obj);
        try {
            if (isEmpty(key) || isEmpty(obj)) {
                return false;
            }
            redisTemplate.opsForValue().set(key, serialize(obj));
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    public Object get(String key) {
        try {
            if (isEmpty(key)) {
                return false;
            }

            return redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 缓存中存入序列化的Object对象
     *
     * @param
     * @param key 缓存key
     * @param obj 存入的序列化对象
     * @return true:成功 false:失败
     */
    public boolean setObj(String key, Object obj, long seconds) {
        LOG.debug(" set key :{}, value:{}, seconds:{}", key, obj, seconds);
        try {
            if (isEmpty(key) || isEmpty(obj)) {
                return false;
            }

            redisTemplate.opsForValue().set(key, obj);
            if (seconds > 0) {
                redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 取出缓存中存储的序列化对象
     *
     * @param key   缓存key
     * @param clazz 对象类
     * @return <T>	序列化对象
     */
    public <T> T getObj(String key, Class<T> clazz) {
        LOG.debug(" get key :{}", key);
        try {
            if (isEmpty(key)) {
                return null;
            }

            return (T) redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 存入Map数组
     *
     * @param <T>
     * @param key 缓存key
     * @param map 缓存map
     * @return true:成功 false:失败
     */
    public <T> boolean setMap(String key, Map<String, T> map) {
        try {
            if (isEmpty(key) || isEmpty(map)) {
                return false;
            }

            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 存入Map数组
     *
     * @param <T>
     * @param key 缓存key
     * @param map 缓存map
     * @return true:成功 false:失败
     */
    public <T> boolean setMap(String key, Map<String, T> map,long day) {
        try {
            if (isEmpty(key) || isEmpty(map)) {
                return false;
            }

            redisTemplate.opsForHash().putAll(key, map);
            if (day > 0) {
                redisTemplate.expire(key, day, TimeUnit.DAYS);
            }
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 取出缓存的map
     *
     * @param key 缓存key
     * @return map    缓存的map
     */
    @SuppressWarnings("rawtypes")
    public Map getMap(String key) {
        LOG.debug(" getMap key :{}", key);
        try {
            if (isEmpty(key)) {
                return null;
            }

            return redisTemplate.opsForHash().entries(key);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 查询缓存的map的集合大小
     *
     * @param key 缓存key
     * @return int    缓存map的集合大小
     */
    public long getMapSize(String key) {
        LOG.debug(" getMap key :{}", key);
        try {
            if (isEmpty(key)) {
                return 0;
            }

            return redisTemplate.opsForHash().size(key);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return 0;
    }


    /**
     * 根据key以及hashKey取出对应的Object对象
     *
     * @param key     缓存key
     * @param hashKey 对应map的key
     * @return object    map中的对象
     */
    public Object getMapKey(String key, String hashKey) {
        LOG.debug(" getMapkey :{}, hashKey:{}", key, hashKey);
        try {
            if (isEmpty(key) || isEmpty(hashKey)) {
                return null;
            }

            return redisTemplate.opsForHash().get(key, hashKey);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 取出缓存中map的所有key值
     *
     * @param key 缓存key
     * @return Set<String> map的key值合集
     */
    public Set<Object> getMapKeys(String key) {
        LOG.debug(" getMapKeys key :{}", key);
        try {
            if (isEmpty(key)) {
                return null;
            }

            return redisTemplate.opsForHash().keys(key);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 删除map中指定的key值
     *
     * @param key     缓存key
     * @param hashKey map中指定的hashKey
     * @return true:成功 false:失败
     */
    public boolean delMapKey(String key, String hashKey) {
        LOG.debug(" delMapKey key :{}, hashKey:{}", key, hashKey);
        try {
            if (isEmpty(key) || isEmpty(hashKey)) {
                return false;
            }

            redisTemplate.opsForHash().delete(key, hashKey);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 存入Map数组
     *
     * @param <T>
     * @param key     缓存key
     * @param map     缓存map
     * @param seconds 秒数
     * @return true:成功 false:失败
     */
    public <T> boolean setMapExp(String key, Map<String, T> map, long seconds) {
        LOG.debug(" setMapExp key :{}, value: {}, seconds:{}", key, map, seconds);
        try {
            if (isEmpty(key) || isEmpty(map)) {
                return false;
            }

            redisTemplate.opsForHash().putAll(key, map);
            redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * map中加入新的key
     *
     * @param <T>
     * @param key     缓存key
     * @param hashKey map的Key值
     * @param value   map的value值
     * @return true:成功 false:失败
     */
    public <T> boolean addMap(String key, String hashKey, T value) {
        LOG.debug(" addMap key :{}, hashKey: {}, value:{}", key, hashKey, value);
        try {
            if (isEmpty(key) || isEmpty(hashKey) || isEmpty(value)) {
                return false;
            }

            redisTemplate.opsForHash().put(key, hashKey, value);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 缓存存入List
     *
     * @param <T>
     * @param key  缓存key
     * @param list 缓存List
     * @return true:成功 false:失败
     */
    public <T> boolean setList(String key, List<T> list) {
        LOG.debug(" setList key :{}, list: {}", key, list);
        try {
            if (isEmpty(key) || isEmpty(list)) {
                return false;
            }

            redisTemplate.opsForList().leftPushAll(key, list.toArray());
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 根据key值取出对应的list合集
     *
     * @param key 缓存key
     * @return List<Object> 缓存中对应的list合集
     */
    public <V> List<V> getList(String key) {
        LOG.debug(" getList key :{}", key);
        try {
            if (isEmpty(key)) {
                return null;
            }

            return (List<V>) redisTemplate.opsForList().range(key, 0, -1);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 根据key值截取对应的list合集
     *
     * @param key   缓存key
     * @param start 开始位置
     * @param end   结束位置
     * @return
     */
    public void trimList(String key, int start, int end) {
        LOG.debug(" trimList key :{}", key);
        try {
            if (isEmpty(key)) {
                return;
            }

            redisTemplate.opsForList().trim(key, start, end);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
    }

    /**
     * 取出list合集中指定位置的对象
     *
     * @param key   缓存key
     * @param index 索引位置
     * @return Object    list指定索引位置的对象
     */
    public Object getIndexList(String key, int index) {
        LOG.debug(" getIndexList key :{}, index:{}", key, index);
        try {
            if (isEmpty(key) || index < 0) {
                return null;
            }

            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * Object存入List
     *
     * @param
     * @param key   缓存key
     * @param value List中的值
     * @return true:成功 false:失败
     */
    public boolean addList(String key, Object value) {
        LOG.debug(" addList key :{}, value:{}", key, value);
        try {
            if (isEmpty(key) || isEmpty(value)) {
                return false;
            }

            redisTemplate.opsForList().leftPush(key, value);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 缓存存入List
     *
     * @param <T>
     * @param key     缓存key
     * @param list    缓存List
     * @param seconds 秒数
     * @return true:成功 false:失败
     */
    public <T> boolean setList(String key, List<T> list, long seconds) {
        LOG.debug(" setList key :{}, value:{}, seconds:{}", key, list, seconds);
        try {
            if (isEmpty(key) || isEmpty(list)) {
                return false;
            }

            redisTemplate.opsForList().leftPushAll(key, list.toArray());
            if (seconds > 0) {
                redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * set集合存入缓存
     *
     * @param <T>
     * @param key 缓存key
     * @param set 缓存set集合
     * @return true:成功 false:失败
     */
    public <T> boolean setSet(String key, Set<T> set) {
        LOG.debug(" setSet key :{}, value:{}", key, set);
        try {
            if (isEmpty(key) || isEmpty(set)) {
                return false;
            }

            redisTemplate.opsForSet().add(key, set.toArray());
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * set集合中增加value
     *
     * @param
     * @param key   缓存key
     * @param value 增加的value
     * @return true:成功 false:失败
     */
    public boolean addSet(String key, Object value) {
        LOG.debug(" addSet key :{}, value:{}", key, value);
        try {
            if (isEmpty(key) || isEmpty(value)) {
                return false;
            }

            redisTemplate.opsForSet().add(key, value);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * set集合存入缓存
     *
     * @param <T>
     * @param key     缓存key
     * @param set     缓存set集合
     * @param seconds 秒数
     * @return true:成功 false:失败
     */
    public <T> boolean setSet(String key, Set<T> set, long seconds) {
        LOG.debug(" setSet key :{}, value:{}, seconds:{}", key, set, seconds);
        try {
            if (isEmpty(key) || isEmpty(set)) {
                return false;
            }

            redisTemplate.opsForSet().add(key, set.toArray());
            if (seconds > 0) {
                redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 取出缓存中对应的set合集
     *
     * @param <T>
     * @param key 缓存key
     * @return Set<Object> 缓存中的set合集
     */
    public <T> Set<T> getSet(String key) {
        LOG.debug(" getSet key :{}", key);
        try {
            if (isEmpty(key)) {
                return null;
            }

            return (Set<T>) redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 有序集合存入数值
     *
     * @param key   缓存key
     * @param value 缓存value
     * @param score 评分
     * @return
     */
    public boolean addZSet(String key, Object value, double score) {
        LOG.debug(" addZSet key :{},value:{}, score:{}", key, value, score);
        try {
            if (isEmpty(key) || isEmpty(value)) {
                return false;
            }

            return redisTemplate.opsForZSet().add(key, value, score);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 从有序集合中删除指定值
     *
     * @param key   缓存key
     * @param value 缓存value
     * @return
     */
    public boolean removeZSet(String key, Object value) {
        LOG.debug(" removeZSet key :{},value:{}", key, value);
        try {
            if (isEmpty(key) || isEmpty(value)) {
                return false;
            }

            redisTemplate.opsForZSet().remove(key, value);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 从有序集合中删除指定位置的值
     *
     * @param key   缓存key
     * @param start 起始位置
     * @param end   结束为止
     * @return
     */
    public boolean removeZSet(String key, long start, long end) {
        LOG.debug(" removeZSet key :{},start:{}, end:{}", key, start, end);
        try {
            if (isEmpty(key)) {
                return false;
            }

            redisTemplate.opsForZSet().removeRange(key, start, end);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 从有序集合中获取指定位置的值
     *
     * @param key   缓存key
     * @param start 起始位置
     * @param end   结束为止
     * @return
     */
    public <T> Set<T> getZSet(String key, long start, long end) {
        LOG.debug(" getZSet key :{},start:{}, end:{}", key, start, end);
        try {
            if (isEmpty(key)) {
                return Collections.emptySet();
            }

            return (Set<T>) redisTemplate.opsForZSet().range(key, start, end);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return Collections.emptySet();
    }
}
